﻿using Mr.Common.Enum;
using Mr.Common.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Mr.Common.Filter
{
    /// <summary>
    /// 登录过滤
    /// </summary>
    public class LoginAttribute :FilterAttribute,IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            bool validateResult = false;
            var request=filterContext.HttpContext.Request;
            if (filterContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute),true).Any())
            {
                return;
            }
            //获取token获取
            var token = request.Headers["UserToken"];
            if (string.IsNullOrEmpty(token))
            {
                //尝试从cookies中获取                
                if (request.Cookies["UserToken"] != null)
                {
                    token = request.Cookies["UserToken"].Value;
                }
            }
            //验证token
            if (!string.IsNullOrEmpty(token))
            {
                validateResult = TokenManager.Validate(token, payLoad =>
                {
                    var success = true;
                    success = success && payLoad["aud"]?.ToString() == "user";
                    return success;
                });
            }
            if(!validateResult)
            {
                if (HttpRequestExtension.IsAjaxRequest(request))
                {
                    var result = new JsonResult();
                    result.ContentType = "text/json";
                    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    result.Data = new Mr.Common.AjaxResult(ResultStatus.NotLogin, "当前未登录");
                    filterContext.Result = result;
                    return;
                }
                else
                {
                    filterContext.HttpContext.Response.Redirect("/Login");
                    filterContext.Result = new EmptyResult();
                    return;
                }
            }
            OnActionExecuting(filterContext);
        }
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {

        }
    }

    public class AllowAnonymousAttribute : ActionFilterAttribute
    {

    }
}
